/// <summary>
/// Generic Mono singleton.
/// </summary>
using UnityEngine;

//T指的是将来的子类型
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T m_Instance = null;

    public static T instance
    {
        get
        {
            if (m_Instance == null)
            {
                m_Instance = GameObject.FindObjectOfType(typeof(T)) as T;
                if (m_Instance == null)
                {
                    m_Instance = new GameObject("Singleton of " + typeof(T).ToString(), typeof(T)).GetComponent<T>();
                    m_Instance.Init();//找到了一个实例,或者创建一个新实例的时候需要初始化
                }
            }
            return m_Instance;
        }
    }

    private void Awake()
    {
        if (m_Instance == null)
        {
            m_Instance = this as T;
            Init();//如果本来场景中的就直接初始化
        }
    }

    public void Create()
    {
    }

    public virtual void Init()
    { }

    private void OnApplicationQuit()
    {
        m_Instance = null;
    }
}